<template>
	<view class="content " :style="{paddingTop: yemiangao+'px'}">

		<view class="d-kuan-juzhong ">
			<!--头部-->
			<view class="d-kuan pc-dingbu">
				<DToubu 
				ref="dToubu" 
				@login-success="handleLoginSuccess"
				@clear-audio="clearAllAudio" 
				@logout-success="handleLogout"
				:dengluxianshi="denglu_xianshi"
				@update-dengluxianshi="handleUpdateDengluxianshi"
				></DToubu>
			</view>

			<!--头部-->
			<!--下面内容-->
			<view class="d-kuan d-clear">
				<uv-row customStyle="margin-bottom: 10px" :gutter="10">
					<uv-col span="2" class="pc-yincang">
						
					</uv-col>
					<uv-col :span="kuan_shu" id="daohangkuan" >
						<view class="d-kuan ">
							<view class="d-neikuang-10 ">

								<view class="d-fanhui-40 " @click="fanhui">
									<uv-icon name="arrow-left" color="#000000" size="18"></uv-icon>
								</view>
							</view>
						</view>
						<view class="d-kuan ">
							<view class="pc-neikuang-20 d-piaofu-shenqing-00" >
							    <view class="d-beijing-baise d-yuanjiao-10 d-bianhua-10" :style="{height: leftNavHeight}">
									<!--daohang-->
									<uv-tabs :list="quan_daohang_list" @click="yiji2" lineColor="#07bfa6" :activeStyle="{ color: '#0a9a87' }"></uv-tabs>
								    <uv-tabs v-if="quan_daohang_list && quan_daohang_list.length > 0 " :key="'erji-' + activeIndex.id"  :current="xuanzezhi" :list="erjidata" @click="erji2" lineColor="#07bfa6" :activeStyle="{ color: '#0a9a87' }"></uv-tabs>
									
									<uv-input  class="d-shang-10" placeholder="圈子名称" border="surround" v-model="title" ></uv-input>
									<uv-textarea class="d-shang-10" count v-model="neirong" placeholder="圈子介绍"></uv-textarea>
									<view class="example-body d-shang-10">
										<uv-upload
											:fileList="fileList1"
											name="1"
											multiple
											
											:maxCount="1"
											@afterRead="afterRead"
											@delete="deletePic"
											
											
											accept="image/*,video/*"
											:previewFullImage="true"
										></uv-upload>
										
									</view>

								</view>
							
							<view class="d-kuan d-jiacu d-wenzi-16  d-piaofu-shenqing-1">
								<uv-button @click="shenqing" class="d-shang-10" type="default" shape="circle"  :plain="true" text="申请圈子"></uv-button>
							</view>
						</view>
						</view>
					</uv-col>
					<uv-col span="3" class="pc-yincang">
						

					</uv-col>
				</uv-row>

				

			</view>
			<!--下面内容-->

		</view>
	</view>
</template>

<script>
    import Api from '@/utils/api.js';
	import QuanApi from '@/utils/quan_api.js';

	//var wxRequest_2 = require("../../utils/wxRequest.js");
	import { getRequest,postRequest } from '@/utils/wxRequest.js';
    //引入组件 d-toubu
    import DToubu from '@/components/d-toubu/d-toubu.vue'
	import Ddaohang from '@/components/d-daohang/d-daohang.vue'
	export default {
		data() {
			return {
				id:'',
				title: '',
				neirong:'',

				leftNavHeight: '0rpx', // 默认高度
				daohangkuanzhi: '50%', // 默认值
				rightColWidth: '300px', // 默认宽度
				rightColLeft: '0px', // 添加这个属性
				daohang_top:'60',

				
				denglu_xianshi:0, // 登录显示
				erjidata:[],
				erjiindex:'',//当前激活的二级菜单索引
				activeIndex: -1, // 当前激活的一级菜单索引
				quan_daohang_list:[], // 知识导航列表
				zhishi_list:[], // 知识列表
				xuanzezhi:0, // 知识列表
				daohanggaoHeight: '54px', // 导航栏高度

				currentPage: 1, //下拉加载
    			pageSize: 12, //下拉加载
    			isLoading: false, //下拉加载
    			noMoreData: false, //下拉加载
				kuan_shu: 8, //格大小
				kuan_quan:6,//格大小
				yemiangao:70, //顶部导航栏
				//上传图片
				fileList1: [],//图片存储
				fabuid:{},//发布id
				uptu:[],

			}
		},
		components: {
  		    DToubu,
			Ddaohang
  		},
		computed: {
		  	yidenglu() {
		  	  return (this.$store.state.memberuid && this.$store.state.keycode) ? 1 : 0;
		  	},
		  	touxiang() {
		  	  return this.$store.state.member? this.$store.state.member.avatar : '';
		  	},
		  	name1() {
		  	  return this.$store.state.member? this.$store.state.member.name : '';
		  	},
			uid() {
		  	  return this.$store.state.memberuid;
		  	},
		  	keycode() {
		  	  return this.$store.state.keycode;
		  	}
		},

		onReachBottom() {
  			this.onReachBottom(); //下拉加载分页
  		},
		mounted() {
			//var m = this.$store.state;
			//console.log('mmmm',m);
			
    	    this.setLeftNavHeight();
			this.getRightColWidth(); // 添加这行
			
    	    // 添加窗口大小变化监听
    	    window.addEventListener('resize', this.setLeftNavHeight);
			window.addEventListener('resize', this.getRightColWidth); // 添加窗口大小变化监听
			this.$nextTick(() => {
				// 计算高度
				//this.calcDaohanggaoHeight();
    		});

    	},
    	beforeDestroy() {
    	    // 移除监听
    	    window.removeEventListener('resize', this.setLeftNavHeight);
			window.removeEventListener('resize', this.getRightColWidth); // 添加这行
			
    	},
		onShow() {
			//var m = this.$store.state;
			//console.log('12300000:', this.$store.state.memberuid);
			this.quan_daohang_api();
			this.getFabuid_api();
			/*var e = this;
			this.zhishi_list_api(e,false);*/
		},
		onLoad(e) {
			// 获取URL参数
			//this.id = e.id || '';
			//console.log('圈子id',this.id);
			
		},
		methods: {
			yiji2(index) {
				this.xuanzezhi = 0;
				this.id = index.id;
				console.log('一级分类id',this.id);
				console.log(this.xuanzezhi);
    		  // 切换激活的一级菜单
			  setTimeout(() => {

    			  	this.activeIndex = index;
    			  	// 根据激活的一级菜单显示对应的二级菜单
				  	if(index.id == 0){
						  this.erjidata = [];
				  	}else{
						  this.erjidata = this.quan_daohang_list[index.index].son;
						  
				  	}
				  	const data = {
						  categories:index.id,
						  page: 1 // 重置页码
				  	}
					this.currentPage = 1; // 重置页码
					this.noMoreData = false; // 重置无更多数据标志
				  	
					  this.calcDaohanggaoHeight();
				}, 300);
    		  
			  
    		},
			erji2(index) {
				this.xuanzezhi = index.index;
				this.id = index.id;
				console.log('二级分类id',this.id);

    		  // 切换激活的二级菜单
    		  this.erjiindex = index.id;
			  this.activeIndex = index;

			  const data = {
				  categories:index.id,
				  page: 1 // 重置页码
			  }
			    this.currentPage = 1; // 重置页码
				this.noMoreData = false; // 重置无更多数据标志

			  
			  //console.log('二级分类：',index);

    		},
			// 发布登录
			denglu_fabu(){
				if(this.yidenglu == 0){
					this.denglu_xianshi = 1;
				} else {
					this.denglu_xianshi = 0;	
				}
				
				console.log('发布登录',this.denglu_xianshi);
				
			},
			// 更新判断是否登录
			handleUpdateDengluxianshi(value) {
			  	this.denglu_xianshi = value;
			  	console.log('关闭登录',this.denglu_xianshi);
			},
			// 退出登录
			handleLogout() {
 			  // 用户退出时关闭阅读界面
 			  this.yuedu = false;

 			  // 停止并销毁音频
 			  if(this.$refs.audioPlayer) {
 			    const audioCtx = this.$refs.audioPlayer.getAudioContext();
 			    audioCtx.stop();
 			    audioCtx.destroy();
 			  }
			   //this.getDianzan_panduan_api(); // 退出登录后重新获取点赞状态
			   //this.getShoucang_panduan_api(); // 退出登录后重新获取收藏判断
 			},
			// 登录
			handleLogin() {
				//this.getDianzan_panduan_api(); // 登录后重新获取点赞状态
				//this.getShoucang_panduan_api(); //登录后重新获取收藏判断
			},



			getRightColWidth() {
				// 获取系统信息
				const query_2 = uni.createSelectorQuery().in(this);
				const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowWidth = systemInfo.windowWidth;
				var d = this;            
               this.$nextTick(() => {
					if(windowWidth >=920){
						query_2.select('#daohangkuan').boundingClientRect(data => {
    		    		    if (data) {
    		    		        this.daohangkuanzhi = `${data.width-150}px`;
    		    		    }
    		    		}).exec();

						d.gao = 20;
						d.kuan_shu = 7;
						d.kuan_quan = 6;
						d.swiperHeight = '250';
						d.daohang_top = '60';
						d.yemiangao = '70';
					} else {
						d.gao = 10;
						d.kuan_shu = 12;
						d.kuan_quan = 12;
						d.swiperHeight = '120';
						d.daohang_top = '80';
						d.yemiangao = '0';
						this.daohangkuanzhi = '100%'; // 或其他适合的默认值


					}

                 const query = uni.createSelectorQuery().in(this);
                 query.select('#youbiankuan').boundingClientRect(rect => {
                   if (rect) {
                     /*this.rightColWidth = `${rect.width+20}px`;
                     console.log('右侧列宽度:', this.rightColWidth);*/
					 	this.rightColWidth = `${rect.width-80}px`;
                    	this.rightColLeft = `${rect.left}px`; // 计算左侧位置
                    	console.log('右侧列位置:', this.rightColWidth);
                   }
                 }).exec();
               });
            },

			calcDaohanggaoHeight() {
				this.$nextTick(() => {

    		    	const query = uni.createSelectorQuery().in(this);
    		    	query.select('#daohanggao').boundingClientRect(data => {
    		    	    if (data) {
    		    	        this.daohanggaoHeight = `${data.height}px`;
							console.log('导航栏高度:', this.daohanggaoHeight);
    		    	    }
    		    	}).exec();
				});
    		},

			//首页
			shouye(){
				uni.navigateTo({
					url: '/pages/index/index',
					fail: (err) => {
						console.error('跳转失败:', err)
					}
				})
			},
			

			toggleErji(index) {
				
    		  if (this.activeIndex === index) {
    		    // 点击已激活的菜单，收起二级菜单
    		    this.activeIndex = -1;
    		    this.currentErji = [];
    		  } else {
    		    // 点击新的菜单，显示对应的二级菜单
    		    this.activeIndex = index;
    		    this.currentErji = this.zhishi_daohang_list[index].erji;
    		  }
    		},
			setLeftNavHeight() {
        	    // 获取系统信息
        	    const systemInfo = uni.getSystemInfoSync();
        	    // 计算可用高度（可根据实际需求调整计算方式）
        	    const windowHeight = systemInfo.windowHeight;
        	    const headerHeight = 70; // 头部高度估计值
        	    const calculatedHeight = windowHeight - headerHeight;
				
        	    // 设置左边导航高度
        	    this.leftNavHeight = `${calculatedHeight}px`;
        	},
			
			
			handleLoginSuccess() {
  			  this.$forceUpdate();
  			},
			// 返回
            fanhui() {
				
               // 获取页面栈
                 const pages = getCurrentPages();
                 // 如果页面栈长度小于等于1，说明没有上一级页面
                 if (pages.length <= 1) {
                    console.log('没有上一级页面');
                    uni.reLaunch({
                      url: '/pages/index/index'
                    });
                 } else {
                    // 有上一级页面则返回
                    uni.navigateBack({
                      delta: 1
                    });
                }
            },
			// 导航接口
			quan_daohang_api(){
				var get_data = getRequest(Api.getQuan_daohang());
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						// 转换时间戳为日期格式
						//var list = res.data ? res.data.data : {};
						var list = res.data && res.data.data ? res.data.data.lisi2 : [];
						
						
        				this.quan_daohang_list = list;
						console.log(list);
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
			},
			//申请圈子
			shenqing(){
				// 如果id为空
				if(!this.id || !this.title || !this.neirong){

					uni.showToast({
						icon: 'none',
						title: '请填写圈子信息'
					});
					return;
				}
				// 弹出确定
				uni.showModal({
					title: '提示',
					content: '确定信息正确吗？',
					success: (res) => {
						if (res.confirm) {
							// 点击确定后的操作
							console.log('用户点击了确定');
							this.shenqing_api();
						} else if (res.cancel) {
							// 点击取消后的操作
							console.log('用户点击了取消');
						}
					}
				});
			},
			// 申请圈子接口
			shenqing_api(){
				const uid = this.$store.state.memberuid;
                const keycode = this.$store.state.keycode;
				// 如果id为空
				if(!this.id || !this.title || !this.neirong){

					uni.showToast({
						icon: 'none',
						title: '请填写圈子信息'
					});
					return;
				}
				// 上传图片
					let img = '';
					var jtu =this.fileList1;
					jtu.forEach(item=>{
						img+= '&data[thumb]='+item.id;
					})
				var datas = "is_ajax=1&data[title]="+this.title+"&data[content]="+this.neirong+"&catid="+this.id+img;

				var post_data = postRequest(QuanApi.postShenqing_quan(uid,keycode,this.id),datas);
				var res;
				post_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						// 转换时间戳为日期格式
						//var list = res.data ? res.data.data : {};
						var list = res.data && res.data.data ? res.data.data.lisi2 : [];
						
						
        				this.quan_daohang_list = list;
						console.log(list);
						//申请成功
						uni.showToast({
							icon: 'success',
							duration: 2000,

							title: '申请成功，等待审核'
						});
						// 跳转到圈子栏目
						uni.switchTab({
							url: '/pages/quan/index',
							fail: (err) => {
								console.error('跳转失败:', err)
							}
						})


					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
			},
			// 新增图片
			async afterRead(event) {
				var duixin = this; 
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
					console.log('event',event); 
					let lists = [].concat(event.file)
					let fileListLen = this[`fileList${event.name}`].length
					lists.map((item) => {
						// 判断文件类型
						const isImage = item.type.startsWith('image/');
						const isVideo = item.type.startsWith('video/');
						
						// 只处理图片和视频文件
						if (isImage || isVideo) {
							this[`fileList${event.name}`].push({
								...item,
								status: 'uploading',
								message: '上传中',
								fileType: isImage ? 'image' : 'video'
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: '不支持的文件类型，请上传图片或视频'
							})
						}
					})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,1)
					const id = duixin.uptu.data.id;
					console.log('uptu',duixin.uptu.data.id); 
					let item = this[`fileList${event.name}`][fileListLen]
					// 更新文件列表状态
						const updatedItem = Object.assign(item, {
							status: 'success',
							message: '',
							url: result,
							id: id,
							fileType: item.fileType // 保留文件类型信息
						})
						this[`fileList${event.name}`].splice(fileListLen, 1, updatedItem)
						fileListLen++
						
						// 注释掉自动插入逻辑，根据用户需求取消自动插入
						// if (updatedItem.fileType === 'image') {
						// 	this.handleInsertImage({ url: result })
						// } else if (updatedItem.fileType === 'video') {
						// 	this.handleInsertVideo({ url: result })
						// }
					}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			//上传图片
			uploadFilePromise(url,leixing) {
				
				
				var duixin = this; 
				console.log('fabuidjiugetu',duixin.fabuid && duixin.fabuid.jiugetu); 
				const uid = this.$store.state.memberuid;
				const keycode = this.$store.state.keycode;
				
				// 图片上传
				var upid = duixin.fabuid && duixin.fabuid.quan_tubiao;
				

				
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: QuanApi.postTupians(uid,keycode)+'&fid='+upid, //
						filePath: url,
						name: 'file_data',
						formData: {
							is_ajax:1
						},
						success: (res) => {
							var duixin = this; 
							if(leixing==1){
								duixin.uptu = JSON.parse(res.data);
								//打印duixin.uptu
								console.log('duixin.uptu',duixin.uptu);
								// 假设接口返回的数据中有img_url字段包含图片URL
								// 使用正确的URL路径，并确保传递给handleInsertImage
								const imgUrl = duixin.uptu.data.url || '';
								console.log('服务器返回的图片URL:', imgUrl);
								setTimeout(() => {
									resolve(imgUrl)
								}, 1000)

							} else if(leixing==2){
								duixin.up_shipin = JSON.parse(res.data);
								//打印duixin.uptu
								console.log('duixin.up_shipin',duixin.up_shipin);
								const shipinUrl = duixin.up_shipin.data.url || '';
								console.log('服务器返回的图片URL:', shipinUrl);
								setTimeout(() => {
									resolve(shipinUrl)
								}, 1000)
							}
							// 注释掉自动插入逻辑，根据用户需求取消自动插入
						// this.handleInsertImage({url: imgUrl});
							
							}
							
					});
				})
			},
			// 关闭播放音频
			clearAllAudio() {
    		  if(this.$refs.audioPlayer) {
    		    const audioCtx = this.$refs.audioPlayer.getAudioContext();
    		    audioCtx.stop();
    		    audioCtx.destroy();
    		  }
    		},
		//发布id
		getFabuid_api(){
			var duixin = this; 
			var get_data = getRequest(Api.getFabuid());
				var res;
				get_data.then(duixin_data => {
					res = duixin_data;
					if(res.data.code) {
						duixin.fabuid = res.data.data;
					} else {
						uni.showToast({
							icon: 'none',
							title: '获取失败，请稍后重试'
						});
					}
				})
		},

			
			
			
			
			

		}
	}
</script>

<style>

	.content {
		display: flex;
		flex-direction: column;
		/*align-items: center;*/
		/*justify-content: center;*/
		/*background-color: #f3f3f3;*/
		
		margin-bottom: 0px;
		
		box-sizing: border-box;
		overflow-x: hidden;

	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	/* 屏幕宽度大于786px时隐藏uni-page-head */
    @media (min-width: 786px) {
        uni-page-head {
            display: none !important;
            opacity: 0 !important;
            height: 0 !important;
            visibility: hidden !important;
        }
    }
	/*.d-daohang{
		
		width: 600rpx;
	}*/
	/* 添加在style部分 */
	.d-daohang-zuo {
    position: fixed;
    left: 0;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #f5f5f5;
    z-index: 100;
	box-shadow: 2px 0 5px rgba(177, 177, 177, 0.1);
  }
  
  .d-daohang-you {
    position: fixed;
    left: 180rpx;
    
    width: 180rpx;
    height: calc(100vh - 70rpx);
    background: #fff;
    z-index: 100;
    box-shadow: 2px 0 5px rgba(0,0,0,0.1);
  }
  .d-erji-item {
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 20rpx;
   /* border-bottom: 1px solid #f0f0f0;*/
  }
  
  .d-erji-item:active {
    background: #f5f5f5;
  }
  .you-guding-1 {
		position: fixed;
		top: 0; /* 根据头部高度调整 */
		/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
		transition: all 0.3s ease;
	}
    .you-guding-2 {
		position: fixed;

		top: 60px; /* 根据头部高度调整 */
		/*box-shadow: -2px 0 5px rgba(0,0,0,0.1);*/
		transition: all 0.3s ease;
	}


	
</style>
